How to fix ValueError: too many values to unpack (expected 2)

您所在的位置:网站首页 many too How to fix ValueError: too many values to unpack (expected 2)

How to fix ValueError: too many values to unpack (expected 2)

2023-04-06 20:23| 来源: 网络整理| 查看: 265

When running Python code with unpacking assignment, you might encounter the following error:

ValueError: too many values to unpack (expected 2)

This error occurs when you have more values on the right hand of the assignment than the variables on the left hand.

There are four possible scenarios where this error might occur:

You unpack too many list values You unpack too many function return values You unpack a dictionary using a for loop You unpack too many values from a CSV file

This tutorial will show you how to fix this error in each scenario.

1. Unpacking list values

This error usually happens when you attempt to unpack an iterable object such as a list or a tuple.

Suppose you have a list of animal names, and you want to assign the list values to variables. You use the unpacking assignment as follows:

animals = ['dog', 'cat', 'bird'] pet_1, pet_2 = animals

Output:

Traceback (most recent call last): File "main.py", line 3, in pet_1, pet_2 = animals ValueError: too many values to unpack (expected 2)

This error occurs because there are three values in the animals list, but you only assign the first two values to the pet_1 and pet_2 variables.

When using the unpacking assignment, Python requires you to specify as many variables as the values stored in the iterable object.

To resolve this error, you need to specify as many variables as the number of values in your list.

In this case, add a third variable to the assignment as follows:

pet_1, pet_2, pet_3 = animals

Notice that you don鈥檛 receive the error when running the code this time.

If you don鈥檛 need the value, you can also use an underscore _ to discard the value:

pet_1, pet_2, _ = animals

The underscore is a special Python syntax that allows you to ignore the unpacked value, which is useful when you don鈥檛 use that value further down in your source code.

2. Unpacking function return values

The same error also occurs when you use the unpacking assignment to a function that returns more values than your variables.

Consider the following example:

def sum(a, b): c = a + b return a, b, c first_number, second_number = sum(2, 4)

The sum() function returns three values: a, b, and c with c being the sum of a and b values.

But the unpacking assignment only assigns the first two values, so the error is raised:

Traceback (most recent call last): File "main.py", line 5, in first_number, second_number = sum(2, 4) ValueError: too many values to unpack (expected 2)

To resolve this error, you need to unpack the third value returned by the function:

first_number, second_number, total = sum(2, 4) print(first_number) # 2 print(second_number) # 4 print(total) # 6

As you can see, the c variable is now assigned to the total variable, and the error is resolved.

3. Unpacking a dictionary using the for loop

Suppose you have a dictionary that contains a car detail as follows:

my_car = { "name": "Toyota", "color": "Silver", "year": "2021", "price": "25000 USD" }

Next, you attempt to unpack the key-value pairs inside the dictionary using a for loop as follows:

for key, value in my_car: print(key+":", value)

Output:

Traceback (most recent call last): File "main.py", line 8, in for key, value in my_car: ValueError: too many values to unpack (expected 2)

You get this error because Python returns a list of the dictionary keys when you put that dictionary as the object to iterate upon.

The for loop above is equivalent to this:

for key, value in ['name', 'color', 'year', 'price']: print(key+":", value)

Which of course doesn鈥檛 work and causes the error.

There are two ways you can resolve this error. First, you can call the dict.items() method to get a list of set objects that are populated with the dictionary key-value pairs:

my_car = { "name": "Toyota", "color": "Silver", "year": "2021", "price": "25000 USD" } for key, value in my_car.items(): print(key+":", value)

Output:

name: Toyota color: Silver year: 2021 price: 25000 USD

Now you can unpack the key-value pair of the dictionary without causing the error.

The second solution is to use only the key value in the for loop as use the key to access the dictionary value:

my_car = { "name": "Toyota", "color": "Silver", "year": "2021", "price": "25000 USD" } for key in my_car: print(key+":", my_car[key])

The output will be the same as the first solution. Feel free to choose the solution you prefer.

4. Unpacking values from a file reader

This error also occurs when you try to unpack values from a file that has too many values in each row.

Suppose you have a .csv file with the following data:

Name, Age, Gender, City John, 25, Male, New York Sarah, 32, Female, London Michael, 45, Male, Sydney Emily, 28, Female, Toronto David, 20, Male, Paris

Next, suppose you want to read each row in the file using a for loop and put them in variables as follows:

import csv with open('data.csv', 'r') as file: reader = csv.reader(file) # Iterate from the second row next(reader) for row in reader: name, age, gender = row print('name:', name) print('age:', age) print('gender:', gender)

You get this error:

Traceback (most recent call last): File "main.py", line 9, in name, age, gender = row ValueError: too many values to unpack (expected 3)

The error occurs because there are 4 values in the row list, but you鈥檙e only unpacking them to 3 variables.

To resolve the error, you need to declare one more variable to assign to the row list. If you don鈥檛 need the City value, you can use _ to discard the value:

name, age, gender, city = row # discard gender and city: name, age, _, _ = row

Both solutions work and you鈥檒l be able to run the code without raising the error.

Conclusion

The error ValueError: too many values to unpack (expected N) occurs in Python when the number of variables you specify is less than the number of values you want to unpack.

To resolve this error, you need to assign the same number of variables as the number of values in the list or tuple you unpack. You can use the _ special variable to discard the values you don鈥檛 need.

I hope this tutorial is helpful. I see you in other tutorials! 馃憢



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3